package com.lw.leetcode.stack;

import java.util.Stack;

/**
 * 946. 验证栈序列
 *
 * @Author liw
 * @Date 2021/5/17 16:36
 * @Version 1.0
 */
public class ValidateStackSequences {

    public static void main(String[] args) {
        ValidateStackSequences test = new ValidateStackSequences();
        int[] a = {1,2,3,4,5};
        int[] b = {1,2,3,4,5};
        boolean b1 = test.validateStackSequences(a, b);
        System.out.println(b1);
    }

    public boolean validateStackSequences(int[] pushed, int[] popped) {

        int length = pushed.length;

        Stack<Integer> stack = new Stack<>();
        int index = 0;
        for (int i = 0; i < length; i++) {
            int value = popped[i];
            if (!stack.isEmpty() && stack.peek() == value) {
                stack.pop();
            } else {
                while (index < length && pushed[index] != value) {
                    stack.add(pushed[index++]);
                }
                index++;
            }
        }
        return stack.isEmpty();
    }

}
